<template>
  <transition name="page-fade" appear>
    <div class="dashboard-container">
      <!-- 页面标题 -->
      <transition name="header-slide" appear>
        <div class="header-section">
          <h1 class="main-title">数据中心</h1>
          <p class="sub-title">实时监控系统运行状态和关键业务指标</p>
          
          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button type="primary" :icon="Upload">上传文档</el-button>
            <el-button type="success" :icon="Download">批量导入</el-button>
            <el-button 
              :icon="Refresh" 
              @click="refreshData" 
              :loading="isRefreshing"
              :disabled="loading.dashboard || loading.trends"
            >
              {{ isRefreshing ? '刷新中...' : '刷新数据' }}
            </el-button>
            <el-tag type="info" style="margin-left: auto;">今日数据</el-tag>
          </div>
        </div>
      </transition>

    <!-- 统计卡片 -->
    <div class="stats-cards-wrapper">
      <transition-group name="card-fade" tag="div" class="stats-cards-container">
        <el-row :gutter="20" class="stats-cards" key="stats-row">
          <el-col :span="6">
            <el-card class="stat-card blue" :class="{ 'loading': loading.dashboard }">
              <div class="card-content">
                <div class="stat-info">
                  <div class="stat-number">
                    <transition name="number-fade" mode="out-in">
                      <span :key="stats.totalMessages">{{ stats.totalMessages || '0' }}</span>
                    </transition>
                  </div>
                  <div class="stat-label">消息总数</div>
                  <div class="stat-change">
                    <el-icon><TrendCharts /></el-icon>
                    <transition name="fade" mode="out-in">
                      <span class="increase" :key="stats.messagesExchangedToday">{{ formatGrowthRate(stats.messagesExchangedToday, stats.totalMessages) }}</span>
                    </transition>
                  </div>
                  <div class="stat-desc">
                    今日新增 
                    <transition name="number-fade" mode="out-in">
                      <span :key="stats.messagesExchangedToday">{{ stats.messagesExchangedToday || 0 }}</span>
                    </transition> 
                    条消息
                  </div>
                </div>
                <div class="stat-icon blue">
                  <el-icon size="40"><ChatLineRound /></el-icon>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="stat-card green" :class="{ 'loading': loading.dashboard }">
              <div class="card-content">
                <div class="stat-info">
                  <div class="stat-number">
                    <transition name="number-fade" mode="out-in">
                      <span :key="stats.totalDocuments">{{ stats.totalDocuments || '0' }}</span>
                    </transition>
                  </div>
                  <div class="stat-label">文档总数</div>
                  <div class="stat-change">
                    <el-icon><TrendCharts /></el-icon>
                    <transition name="fade" mode="out-in">
                      <span class="increase" :key="stats.documentsUploadedToday">{{ formatGrowthRate(stats.documentsUploadedToday, stats.totalDocuments) }}</span>
                    </transition>
                  </div>
                  <div class="stat-desc">
                    今日新增 
                    <transition name="number-fade" mode="out-in">
                      <span :key="stats.documentsUploadedToday">{{ stats.documentsUploadedToday || 0 }}</span>
                    </transition> 
                    份文档
                  </div>
                </div>
                <div class="stat-icon green">
                  <el-icon size="40"><Document /></el-icon>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="stat-card orange" :class="{ 'loading': loading.dashboard }">
              <div class="card-content">
                <div class="stat-info">
                  <div class="stat-number">
                    <transition name="number-fade" mode="out-in">
                      <span :key="stats.totalUsers">{{ stats.totalUsers || '0' }}</span>
                    </transition>
                  </div>
                  <div class="stat-label">用户总数</div>
                  <div class="stat-change">
                    <el-icon><TrendCharts /></el-icon>
                    <transition name="fade" mode="out-in">
                      <span class="increase" :key="stats.activeUsersToday">{{ formatGrowthRate(stats.activeUsersToday, stats.totalUsers) }}</span>
                    </transition>
                  </div>
                  <div class="stat-desc">
                    今日新增 
                    <transition name="number-fade" mode="out-in">
                      <span :key="stats.activeUsersToday">{{ stats.activeUsersToday || 0 }}</span>
                    </transition> 
                    位用户
                  </div>
                </div>
                <div class="stat-icon orange">
                  <el-icon size="40"><User /></el-icon>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="stat-card purple" :class="{ 'loading': loading.dashboard }">
              <div class="card-content">
                <div class="stat-info">
                  <div class="stat-number">
                    <transition name="number-fade" mode="out-in">
                      <span :key="stats.totalConversations">{{ stats.totalConversations || '0' }}</span>
                    </transition>
                  </div>
                  <div class="stat-label">对话总数</div>
                  <div class="stat-change">
                    <el-icon><TrendCharts /></el-icon>
                    <transition name="fade" mode="out-in">
                      <span class="increase" :key="stats.conversationsToday">{{ formatGrowthRate(stats.conversationsToday, stats.totalConversations) }}</span>
                    </transition>
                  </div>
                  <div class="stat-desc">
                    今日新增 
                    <transition name="number-fade" mode="out-in">
                      <span :key="stats.conversationsToday">{{ stats.conversationsToday || 0 }}</span>
                    </transition> 
                    场对话
                  </div>
                </div>
                <div class="stat-icon purple">
                  <el-icon size="40"><TrendCharts /></el-icon>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </transition-group>
    </div>

    <!-- 图表区域 -->
    <transition name="charts-fade" appear>
      <el-row :gutter="20" class="charts-section">
        <!-- 消息趋势分析 -->
        <el-col :span="12">
          <el-card class="chart-card" :class="{ 'loading': loading.trends }">
            <template #header>
              <div class="chart-header">
                <h3><el-icon><ChatLineRound /></el-icon> 消息趋势分析</h3>
                <el-tag size="small" type="info">最近7天</el-tag>
              </div>
            </template>
            <div class="chart-container" ref="messageChartRef">
              <transition name="chart-content" mode="out-in">
                <div v-if="!trendsData.length" class="chart-placeholder" key="loading">
                  <el-icon class="loading-icon"><Loading /></el-icon>
                  <span>数据加载中...</span>
                </div>
                <div v-else class="trend-chart" key="content">
                  <transition-group name="trend-item" tag="div">
                    <div v-for="(item, index) in trendsData" :key="`msg-${item.date}`" class="trend-item" :style="{ transitionDelay: `${index * 100}ms` }">
                      <div class="trend-date">{{ formatDate(item.date) }}</div>
                      <div class="trend-bars">
                        <div class="trend-bar-item">
                          <div class="trend-icon messages">
                            <el-icon size="14"><ChatLineRound /></el-icon>
                          </div>
                          <span class="trend-label">消息</span>
                          <div class="trend-bar">
                            <div class="trend-progress messages" :style="{ width: getTrendWidth(item.messages, maxValues.messages) + '%' }"></div>
                          </div>
                          <transition name="number-fade" mode="out-in">
                            <span class="trend-value" :key="item.messages">{{ item.messages }}</span>
                          </transition>
                        </div>
                      </div>
                    </div>
                  </transition-group>
                </div>
              </transition>
            </div>
          </el-card>
        </el-col>
        
        <!-- 活动趋势分析 -->
        <el-col :span="12">
          <el-card class="chart-card" :class="{ 'loading': loading.trends }">
            <template #header>
              <div class="chart-header">
                <h3><el-icon><TrendCharts /></el-icon> 活动趋势分析</h3>
                <el-tag size="small" type="success">最近7天</el-tag>
              </div>
            </template>
            <div class="chart-container" ref="activityChartRef">
              <transition name="chart-content" mode="out-in">
                <div v-if="!trendsData.length" class="chart-placeholder" key="loading">
                  <el-icon class="loading-icon"><Loading /></el-icon>
                  <span>数据加载中...</span>
                </div>
                <div v-else class="trend-chart" key="content">
                  <transition-group name="trend-item" tag="div">
                    <div v-for="(item, index) in trendsData" :key="`activity-${item.date}`" class="trend-item" :style="{ transitionDelay: `${index * 100}ms` }">
                      <div class="trend-date">{{ formatDate(item.date) }}</div>
                      <div class="trend-bars">
                        <div class="trend-bar-item">
                          <div class="trend-icon documents">
                            <el-icon size="14"><Document /></el-icon>
                          </div>
                          <span class="trend-label">文档</span>
                          <div class="trend-bar">
                            <div class="trend-progress documents" :style="{ width: getTrendWidth(item.documents, maxValues.documents) + '%' }"></div>
                          </div>
                          <transition name="number-fade" mode="out-in">
                            <span class="trend-value" :key="item.documents">{{ item.documents }}</span>
                          </transition>
                        </div>
                        <div class="trend-bar-item">
                          <div class="trend-icon conversations">
                            <el-icon size="14"><User /></el-icon>
                          </div>
                          <span class="trend-label">对话</span>
                          <div class="trend-bar">
                            <div class="trend-progress conversations" :style="{ width: getTrendWidth(item.conversations, maxValues.conversations) + '%' }"></div>
                          </div>
                          <transition name="number-fade" mode="out-in">
                            <span class="trend-value" :key="item.conversations">{{ item.conversations }}</span>
                          </transition>
                        </div>
                      </div>
                    </div>
                  </transition-group>
                </div>
              </transition>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </transition>
  </div>
  </transition>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Document, ChatLineRound, TrendCharts, Upload, Download, Refresh, Loading } from '@element-plus/icons-vue'
import { dashboardApi } from '@/api'

const stats = ref({})
const trendsData = ref([])
const maxValues = ref({ messages: 1, documents: 1, conversations: 1 })

const loading = ref({
  dashboard: false,
  trends: false
})

const isRefreshing = ref(false)
const messageChartRef = ref()
const activityChartRef = ref()

// 格式化时间
const formatTime = (time) => {
  if (!time) return '无'
  return new Date(time).toLocaleString('zh-CN')
}

// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return `${date.getMonth() + 1}/${date.getDate()}`
}

// 计算增长率
const formatGrowthRate = (todayCount, totalCount) => {
  if (!totalCount || totalCount === 0) return '0%'
  const rate = ((todayCount || 0) / totalCount) * 100
  return rate.toFixed(1) + '%'
}

// 计算趋势条宽度
const getTrendWidth = (value, maxValue) => {
  if (maxValue === 0) return 0
  return Math.max((value / maxValue) * 100, 5) // 最小宽度5%
}

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    loading.value.dashboard = true
    // 获取概览统计
    const overviewData = await dashboardApi.getDashboardOverview()
    stats.value = overviewData
    
    console.log('仪表盘数据:', stats.value)

  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    ElMessage.error('获取仪表盘数据失败')
  } finally {
    loading.value.dashboard = false
  }
}

// 获取趋势数据
const fetchTrendsData = async () => {
  try {
    loading.value.trends = true
    const trendsResponse = await dashboardApi.getDailyTrends()
    trendsData.value = trendsResponse
    
    // 计算最大值用于图表缩放
    maxValues.value = {
      messages: Math.max(...trendsResponse.map(item => item.messages), 1),
      documents: Math.max(...trendsResponse.map(item => item.documents), 1),
      conversations: Math.max(...trendsResponse.map(item => item.conversations), 1)
    }
    
    console.log('趋势数据:', trendsData.value)
    console.log('最大值:', maxValues.value)

  } catch (error) {
    console.error('获取趋势数据失败:', error)
    ElMessage.error('获取趋势数据失败')
  } finally {
    loading.value.trends = false
  }
}

// 刷新数据
const refreshData = async () => {
  isRefreshing.value = true
  await Promise.all([
    fetchDashboardData(),
    fetchTrendsData()
  ])
  isRefreshing.value = false
  ElMessage.success('数据已刷新')
}

// 组件挂载时获取数据
onMounted(async () => {
  await Promise.all([
    fetchDashboardData(),
    fetchTrendsData()
  ])
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题区域 */
.header-section {
  margin-bottom: 24px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.sub-title {
  font-size: 14px;
  color: #666;
  margin: 0 0 20px 0;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 统计卡片样式 */
.stats-cards-wrapper {
  margin-bottom: 24px;
}

.stats-cards-container {
  position: relative;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-card.loading {
  opacity: 0.7;
  transform: scale(0.98);
}

.card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-number .unit {
  font-size: 18px;
  font-weight: 500;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.stat-change {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 8px;
}

.stat-change .increase {
  color: #52c41a;
  font-weight: 600;
  font-size: 12px;
}

.stat-desc {
  font-size: 12px;
  color: #999;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.1;
}

.stat-icon.blue {
  background-color: #1890ff;
  color: #1890ff;
}

.stat-icon.green {
  background-color: #52c41a;
  color: #52c41a;
}

.stat-icon.orange {
  background-color: #fa8c16;
  color: #fa8c16;
}

.stat-icon.purple {
  background-color: #722ed1;
  color: #722ed1;
}

/* 卡片颜色主题 */
.stat-card.blue {
  background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
  border-left: 4px solid #1890ff;
}

.stat-card.green {
  background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
  border-left: 4px solid #52c41a;
}

.stat-card.orange {
  background: linear-gradient(135deg, #fff7e6 0%, #ffd591 100%);
  border-left: 4px solid #fa8c16;
}

.stat-card.purple {
  background: linear-gradient(135deg, #f9f0ff 0%, #efdbff 100%);
  border-left: 4px solid #722ed1;
}

/* 图表区域 */
.charts-section {
  margin-top: 24px;
}

.chart-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.chart-card.loading {
  opacity: 0.7;
  transform: scale(0.98);
}

.chart-card :deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 24px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-header h3 .el-icon {
  color: #1890ff;
}

.time-tabs {
  margin-left: auto;
}

.chart-container {
  height: 400px;
  padding: 20px;
}

.chart-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
  border: 2px dashed #e9ecef;
  border-radius: 8px;
  color: #6c757d;
  font-size: 16px;
  gap: 8px;
}

.loading-icon {
  animation: rotate 2s linear infinite;
  color: #1890ff;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 趋势图表样式 */
.trend-chart {
  height: 100%;
  overflow-y: auto;
  padding: 10px 0;
}

.trend-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.trend-item:last-child {
  border-bottom: none;
}

.trend-date {
  width: 60px;
  font-size: 12px;
  color: #666;
  font-weight: 500;
  flex-shrink: 0;
}

.trend-bars {
  flex: 1;
  margin-left: 16px;
}

.trend-bar-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.trend-bar-item:last-child {
  margin-bottom: 0;
}

.trend-icon {
  width: 24px;
  height: 24px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  flex-shrink: 0;
}

.trend-icon.messages {
  background: linear-gradient(135deg, #e6f7ff, #bae7ff);
  color: #1890ff;
}

.trend-icon.documents {
  background: linear-gradient(135deg, #f6ffed, #d9f7be);
  color: #52c41a;
}

.trend-icon.conversations {
  background: linear-gradient(135deg, #f9f0ff, #efdbff);
  color: #722ed1;
}

.trend-label {
  width: 40px;
  font-size: 12px;
  color: #666;
  flex-shrink: 0;
  font-weight: 500;
}

.trend-bar {
  flex: 1;
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  margin: 0 12px;
  overflow: hidden;
  position: relative;
}

.trend-progress {
  height: 100%;
  border-radius: 4px;
  transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.trend-progress::after {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% { left: -100%; }
  100% { left: 100%; }
}

.trend-progress.messages {
  background: linear-gradient(90deg, #1890ff, #40a9ff);
  box-shadow: 0 0 8px rgba(24, 144, 255, 0.3);
}

.trend-progress.documents {
  background: linear-gradient(90deg, #52c41a, #73d13d);
  box-shadow: 0 0 8px rgba(82, 196, 26, 0.3);
}

.trend-progress.conversations {
  background: linear-gradient(90deg, #722ed1, #9254de);
  box-shadow: 0 0 8px rgba(114, 46, 209, 0.3);
}

.trend-value {
  width: 35px;
  font-size: 12px;
  color: #333;
  font-weight: 600;
  text-align: right;
  flex-shrink: 0;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  display: inline-block;
}

/* 动画效果 */
/* 页面淡入动画 */
.page-fade-enter-active {
  transition: all 0.8s cubic-bezier(0.4, 0, 0.2, 1);
}

.page-fade-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

/* 标题滑入动画 */
.header-slide-enter-active {
  transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

.header-slide-enter-from {
  opacity: 0;
  transform: translateY(-20px);
}

/* 卡片淡入动画 */
.card-fade-enter-active,
.card-fade-leave-active {
  transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

.card-fade-enter-from {
  opacity: 0;
  transform: translateY(30px) scale(0.95);
}

.card-fade-leave-to {
  opacity: 0;
  transform: translateY(-30px) scale(0.95);
}

/* 数字变化动画 */
.number-fade-enter-active,
.number-fade-leave-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.number-fade-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.number-fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

/* 通用淡入淡出 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 图表区域动画 */
.charts-fade-enter-active {
  transition: all 0.8s cubic-bezier(0.4, 0, 0.2, 1);
  transition-delay: 0.3s;
}

.charts-fade-enter-from {
  opacity: 0;
  transform: translateY(40px);
}

/* 图表内容切换动画 */
.chart-content-enter-active,
.chart-content-leave-active {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.chart-content-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.98);
}

.chart-content-leave-to {
  opacity: 0;
  transform: translateY(-20px) scale(0.98);
}

/* 趋势条目动画 */
.trend-item-enter-active {
  transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

.trend-item-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.trend-item-move {
  transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-section .el-col {
    margin-bottom: 20px;
  }
  
  .charts-section .el-col:last-child {
    margin-bottom: 0;
  }
}

@media (max-width: 768px) {
  .stats-cards .el-col {
    margin-bottom: 16px;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
  
  .chart-container {
    height: 300px;
    padding: 16px;
  }
  
  .trend-date {
    width: 50px;
  }
  
  .trend-icon {
    width: 20px;
    height: 20px;
    margin-right: 6px;
  }
  
  .trend-label {
    width: 35px;
  }
  
  .trend-value {
    width: 30px;
    padding: 1px 4px;
  }
}
</style>
